package god.dream.user.controller;

import god.dream.user.model.User;
import god.dream.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UserFormController extends SimpleFormController {

	@Autowired
	private UserService userService;

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = null;
		if (!isFormSubmission(request)) {
			id = request.getParameter("id");
			User user = new User();
			request.setAttribute("mode", "insert");
			if (id != null){
				user = userService.findUser(Integer.parseInt(id));
				request.setAttribute("mode", "update");
			}
			return user;
		} else {
			return (User) super.formBackingObject(request);
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		User user = (User) command;

		try {
			String mode = request.getParameter("mode");
			if("insert".equals(mode))
				userService.addUser(user);
			else if("update".equals(mode))
				userService.updateUser(user);			

			ModelAndView mav = new ModelAndView();
			mav.setViewName(getSuccessView());
			return mav;
		} catch (Exception e) {
			e.printStackTrace();
			return showForm(request, response, errors);
		}
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
}
